package keepalived_logic

import (
	"context"
	"strings"
	"time"
	"yunzhan/common/utils"
	agent "yunzhan/rpc-server/pb"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryKeepalivedConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewQueryKeepalivedConfigLogic 获取Keepalived配置
func NewQueryKeepalivedConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryKeepalivedConfigLogic {
	return &QueryKeepalivedConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryKeepalivedConfigLogic) QueryKeepalivedConfig(req *types.QueryConfigRequest) (resp *types.BaseConfigResponse, err error) {

	agentPort := strings.Split(l.svcCtx.Config.RpcService.ListenOn, ":")[1]

	conn, err := utils.SafeNewClient(req.NodeHost, agentPort)
	if err != nil {
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "创建rpc链接异常",
		}, err
	}

	ctx, cancel := context.WithTimeout(l.ctx, 10*time.Second)
	defer cancel()

	client := agent.NewKeepalivedDeployClient(conn.Conn())
	keepalivedConfig, err := client.GetKeepalivedConfig(ctx, &agent.GetKeepalivedConfRequest{
		NodeHost:  req.NodeHost,
		ClusterID: req.ClusterID,
	})
	if err != nil {
		return &types.BaseConfigResponse{
			Code:    500,
			Message: "查询配置失败",
		}, err
	}

	return &types.BaseConfigResponse{
		Code:    keepalivedConfig.Code,
		Message: keepalivedConfig.Message,
		Data:    keepalivedConfig.Content,
	}, nil
}
